# https://zhuanlan.zhihu.com/p/68197380?utm_id=0

from qgis.PyQt.QtCore import (pyqtSignal)
from qgis.PyQt.QtWidgets import *

# https://www.cnblogs.com/zhiyiYo/p/15676079.html

if __name__ != '__main__':
    from .photoviewer import *


class Photowidget(QWidget):
    img_changed = pyqtSignal()

    def __init__(self, imgs, parent=None):
        super(Photowidget, self).__init__(parent)
        self.imgs = imgs
        self.img_index = 0
        self.initUI()
        # signal connected
        self.img_changed.connect(self.slot_img_changed)

    def initUI(self):
        self.move(200, 200)
        self.grabKeyboard()
        self.setFocusPolicy(Qt.StrongFocus)

        img = QPixmap.fromImage(self.imgs[self.img_index])
        self.viewer = PhotosViewer(img)

        self.img_label = QLabel('1')
        self.img_label.setAlignment(Qt.AlignCenter)

        self.rotate_btn = QPushButton()
        self.rotate_btn.setFixedSize(20, 20)
        self.rotate_btn.setIcon(QIcon(':/plugins/liwftcplugin/resource/rotate.png'))
        self.rotate_btn.clicked.connect(self.slot_rotate_photo)

        self.HBoxLayout = QHBoxLayout()
        self.HBoxLayout.addWidget(self.rotate_btn)
        self.VBoxLayout = QVBoxLayout()
        self.VBoxLayout.addWidget(self.img_label)
        self.VBoxLayout.addWidget(self.viewer)
        self.VBoxLayout.addLayout(self.HBoxLayout)
        self.setLayout(self.VBoxLayout)

    def extentbutton(self):
        self.viewer.zoom_data = []
        self.viewer.fitInView(self.viewer.sceneRect(), Qt.KeepAspectRatio)
        self.viewer.panSelect = False
        self.viewer.zoomSelect = False
        self.viewer.setCursor(Qt.ArrowCursor)
        self.viewer.setDragMode(QGraphicsView.NoDrag)

    def slot_next_photo(self):
        try:
            self.img_index = self.img_index + 1 if self.img_index < len(self.imgs) - 1 else 0
            self.img_changed.emit()
        except:
            print(f'no more imgs')
            return

    def previous_photo(self):
        try:
            self.img_index = self.img_index - 1 if self.img_index > 0 else len(self.imgs) - 1
            self.img_changed.emit()
        except:
            print(f'no more imgs')
            return

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Right:
            self.slot_next_photo()
        if e.key() == Qt.Key_Left:
            self.previous_photo()
        self.img_changed.emit()

    def slot_img_changed(self):
        self.img_label.setText(str(self.img_index + 1))
        img = QPixmap.fromImage(self.imgs[self.img_index])
        self.viewer.setImage(img)

    def slot_rotate_photo(self):
        self.viewer.rotate(90)
